package com.app.twth.scan;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;


public class IDataScan {

    private static final String RES_ACTION = "android.intent.action.SCANRESULT";
    private ScannerInterface mScannerInterface;
    private Context mContext;
    private OnScanListener mOnScanListener;

    //注册广播接受者
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //注意Extral为"value"
            String scanResult = intent.getStringExtra("value");
            if (RES_ACTION.equals(RES_ACTION)) {
                if (scanResult.length() > 0) {
                    //如果条码长度>0，解码成功,否则失败
                    if (mOnScanListener != null) {
                        mOnScanListener.scanSuccess(scanResult);
                    }
                } else {//解码失败
                    mOnScanListener.scanFailed("解码失败");
                }
            }
        }
    };

    public void initScan(Context context, OnScanListener listener) {
        this.mContext = context;
        this.mOnScanListener = listener;
        mScannerInterface = new ScannerInterface(context);
        //设置扫描结果的输出模式
        mScannerInterface.setOutputMode(1);
        IntentFilter filter = new IntentFilter();
        filter.addAction(RES_ACTION);
        context.registerReceiver(mScanReceiver, filter);
    }

    public void destroy() {
        Log.i("IDataScan", "=======注销idata品牌pda广播=========");
        if (mScanReceiver != null && mContext != null) {
            mContext.unregisterReceiver(mScanReceiver);
        }
    }

    public interface OnScanListener {
        void scanSuccess(String code);

        void scanFailed(String message);
    }
}
